<?php

namespace App\Http\Controllers\Home;

use App\Model\Checkgroup;
use App\Model\Commanager;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CompanyRequest;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

use App\Model\Comhealthofficer;
use App\Model\Comsafeofficer;
use App\Model\Comspecialequipmentofficer;
use App\Model\Comspecialworkofficer;
use App\Model\Company;
use App\Model\Comcheck;
use App\Model\Comnature;
use App\Model\Comcheckstep;
use App\Model\Area;
use phpDocumentor\Reflection\Project;
use Carbon\Carbon;
use App\Model\Comcheckdetail;
use App\Model\Comcheckagain;
use App\Model\Comcheckagaindetail;
use App\Model\Checkcategory;
use Illuminate\Support\Facades\DB;

class NinesmallController extends Controller
{
    //九小场所
    public function index()
    {
        return view('ninesmall.index');
    }
    public function indexelse()
    {
        return view('ninesmall.indexelse');
    }
    //分类信息
    public function category(Request $request,int $categoryId)
    {
        $project = \App\Model\Project::all();
        $provinces = Area::where(['level'=>1])->select('id','name')->get();
        $city = Area::where(['pid'=>370000])->select('id','name')->get();
        $district = Area::where(['pid'=>370200])->select('id','name')->get();
        $request->session()->put('categoryId', $categoryId);
        if (Auth::user()->type == 3){
            $name = '';
            $companyCom = Company::where('comName','like','%'.$name.'%')->where(['categoryId'=>$categoryId]);
            $companys = $companyCom->get();
            $type = Auth::user()->type;
            return view('ninesmall/search')
                ->with('categoryId',$categoryId)
                ->with('companys',$companys)
                ->with('type',$type)
                ->with('name',$name);
        }
        $type = Auth::user()->type;
        return view('ninesmall.category')
            ->with('provinces',$provinces)
            ->with('categoryId',$categoryId)
            ->with('district',$district)
            ->with('city',$city)
            ->with('type',$type)
            ->with('project',$project);
    }

    public function get(int $companyId)
    {
        $project = \App\Model\Project::all();
        $company = Company::find($companyId);
        $city = Area::find($company->city);
        $district = Area::find($company->district);
        $street = Area::find($company->street);
        $safeoffer = Comsafeofficer::where(['companyId' => $companyId])->get();
        $manager = Commanager::where(['companyId' => $companyId])->get();
        if(!$company) {
            \Session::flash('error', '公司信息有误!');
            return back();
        }
        $type = Auth::user()->type;
        $provinces = Area::where(['level'=>1])->select('id','name')->get();
        return view('ninesmall.category')
            ->with('categoryId',$company->categoryId)
            ->with('provinces',$provinces)
            ->with('city',$city->name)
            ->with('district',$district->name)
            ->with('safeoffer',$safeoffer)
            ->with('manager',$manager)
            ->with('street',$street->name)
            ->with('project',$project)
            ->with('type',$type)
            ->with('company',$company);
    }

    /**
     * @param Request $quest
     * @return \Illuminate\Http\RedirectResponse
     * 全部企业
     */
    public function search(Request $quest)
    {
        $categoryId = $quest->input('categoryId');
        if(!$categoryId) {
            \Session::flash('error', '公司信息有误!');
            return back();
        }
        $name = $quest->input('name');
//        $user = Auth::user();//获取全部企业
        $companyCom = Company::where('comName','like','%'.$name.'%')->where(['categoryId'=>$categoryId]);
//        if($user->role == 'admin') {
        $companys = $companyCom->get();
//        } else {
//            $companys = $companyCom->where(['userId'=>$user->id])->get();
//        }
        if($name) {
            foreach($companys as $k => $v) {
                $companys[$k]->comName = preg_replace("/($name)/i",
                    "<font color=red><b>\\1</b></font>",
                    $v->comName);
            }
        }
        $type = Auth::user()->type;
        return view('ninesmall/search')
            ->with('categoryId',$categoryId)
            ->with('companys',$companys)
            ->with('type',$type)
            ->with('name',$name);

    }

    public function companyone(Request $request,$companyId)
    {
        $id = $companyId;
//        $user = Auth::user();//获取全部企业
        $companyCom = Company::where(['id'=>$id]);
//        if($user->role == 'admin') {
        $companys = $companyCom->get();
//        } else {
//            $companys = $companyCom->where(['userId'=>$user->id])->get();
//        }
        $type = Auth::user()->type;
        return view('ninesmall/companyone')
            ->with('companys',$companys)
            ->with('type',$type);

    }
    public function getcompany(Request $request,$street,$startdate,$enddate)
    {
        $companyCom = Company::leftJoin('comcheck','comcheck.companyId','company.id')->where('company.street','=',$street)->where('comcheck.created', '>=',$startdate)->where('comcheck.created', '<=', $enddate);
        $companys = $companyCom->get();
        $type = Auth::user()->type;
        return view('ninesmall/companyone')
            ->with('companys',$companys)
            ->with('type',$type);

    }
    /*获取复查公司列表*/
    public function getcompanyagain(Request $request,$street,$startdate,$enddate)
    {
        $where = array();
        $where[] = array('company.schedule','>=', 2);
        $where[] = array('company.type', 2);
        if(!empty($name)) {
            $where[] = array('company.street', '=', $street);
        }

        $fields = array("company.id","company.comName");
        $startdate = strtotime($startdate);
        $enddate = strtotime($enddate);
//        $companies = Company::leftJoin('comcheckagain','comcheckagain.companyId','company.id')->where($where)->where('comcheckagain.checkTime', '>=',$startdate)->where('comcheckagain.checkTime', '<=', $enddate)->select($fields)->get();
        $companies = Company::where($where)->select($fields)->get();

        return view('smallplacecheck.companylist', array(
                'companies' => $companies
            )
        );
    }

    /**
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 我的企业
     */
    public function mysearch(Request $quest)
    {
        $name = '';
        $user = Auth::user();//获取我添加的企业
        if (!empty($_POST)){
            $name = $quest->input('name');
        }
        $companyCom = Company::where('comName','like','%'.$name.'%');
        if($user->role == 'admin') {
            $companys = $companyCom->get();
        } else {
            $companys = $companyCom->where(['userId'=>$user->id])->get();
        }
        if($name) {
            foreach($companys as $k => $v) {
                $companys[$k]->comName = preg_replace("/($name)/i",
                    "<font color=red><b>\\1</b></font>",
                    $v->comName);
            }
        }
        return view('ninesmall/mysearch')
            ->with('companys',$companys)
            ->with('name',$name);
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * 按项目统计
     */
    public function ProjectStatistics(){
//        dd($_GET['project']);
        $project_id = $_GET['project'];
        $today = Carbon::now()->toDateString();
        $list  = Comcheck::leftJoin('company','comcheck.companyId','company.id')->select('comcheck.*','company.project')->where('company.project','=',$project_id)->orderBy('comcheck.id','desc')->get();
        $count = $list->count();
        $comcheckId = [];
        $companyId = [];
        $userId = [];
        foreach ($list as $k=>$v){
            in_array($v['companyId'],$companyId)?'':$companyId[] = $v['companyId'];
            $userId[] = $v['userId'];
            $comcheckId[] = $v['id'];
        }
        $count = count($companyId);
        $comcheckdetail = Comcheckdetail::whereIn('checkId',$comcheckId)->where('status','=',2)->get();        //初查隐患详情
        $comcheckagain = Comcheckagain::whereIn('checkId',$comcheckId)->get();        //复查隐患详情
        $comcheckagainId = [];
        foreach ($comcheckagain as $k=>$v){
            $comcheckagainId[] =$v['id'];
        }
        $comcheckagaindetail = Comcheckagaindetail::whereIn('checkId',$comcheckagainId)->where('status','=',3)->get();
        /**获取省市地区街道信息*/
        $company = Company::whereIn('id',$companyId)->get();
        $areaid = [];
        foreach ($company as $k=>$v){
            (in_array($v->province,$areaid)||(empty($v->province)))?'':array_push($areaid,$v->province);
            (in_array($v->city,$areaid)||(empty($v->city)))?'':array_push($areaid,$v->city);
            (in_array($v->district,$areaid)||(empty($v->district)))?'':array_push($areaid,$v->district);
            (in_array($v->street,$areaid)||(empty($v->street)))?'':array_push($areaid,$v->street);
        }
        $area = Area::whereIn('id',$areaid)->get();
        /**获取省市地区街道信息*/
        return view('project/project_statistics',[
            'list'=>$list,
            'count'=>$count,
            'comcheckdetail'=>$comcheckdetail,
            'comcheckagain'=>$comcheckagain,
            'comcheckagaindetail'=>$comcheckagaindetail,
            'area'=>$area,
        ]);

    }

    public function create(CompanyRequest $request)
    {
        $company = $request->input('company');
        $safeInfo = $request->input('safe');
        $managerInfo = $request->input('manger');

        $categoryId = $company['categoryId'];
//        $project_id = $request->input('project_id');
//        if(empty($project_id)) {
//            \Session::flash('error', '请选择项目类型!');
//            return back();
//        }
//        if(empty($safeInfo['name'][0])) {
//            \Session::flash('error', '安全管理人员未填写!');
//            return back();
//        }

//        if(empty($safeInfo['phone'][0])) {
//            \Session::flash('error', '安全管理人员电话未填写!');
//            return back();
//        }

//        if(empty($managerInfo['name'][0])) {
//            \Session::flash('error', '主要负责人员姓名未填写!');
//            return back();
//        }
//
//        if(empty($managerInfo['phone'][0])) {
//            \Session::flash('error', '主要负责人员电话未填写!');
//            return back();
//        }
//        if(empty($managerInfo['wx'][0])) {
//            \Session::flash('error', '主要负责人员微信号未填写!');
//            return back();
//        }

//        if(empty($company['photo'])) {
//            \Session::flash('error', '请上传门头照片!');
//            return back();
//        }
//        if(empty($company['license'])) {
//            \Session::flash('error', '请上传营业执照!');
//            return back();
//        }
        if(empty($company['leader'])) {
            \Session::flash('error', '请填写法定代表人姓名!');
            return back();
        }
        if(empty($company['area'])) {
            \Session::flash('error', '请填写建筑面积!');
            return back();
        }
        if(empty($company['accompany'])) {
            \Session::flash('error', '请填写企业陪同人员!');
            return back();
        }
        if(empty($company['workersNum'])) {
            \Session::flash('error', '请填写员工人数!');
            return back();
        }


        if(empty($company['space'])) {
            \Session::flash('error', '请填写占地面积!');
            return back();
        }
        $id = $request->input('id',0);
        if($id){
//            dd($id);
            if(!$company['comName'] || !$company['street'])
            {
                \Session::flash('error', '公司信息有误!');
                return back();
            }
            $safeId = $request->input('safeId');
            unset($company['categoryId']);
//            $company['project'] = $project_id;
            Company::where(['id'=>$id])->update($company);
            Comsafeofficer::where(['companyId'=>$id])->delete();
            Commanager::where(['companyId'=>$id])->delete();
//            dd('ss');
            if(!empty($safeInfo))
            {
                $safeInfoData = array();
                $safeInfoData = $safeInfo;
                if(!empty($safeInfoData)) {
                    foreach ($safeInfoData['name'] as $k=>$v){
                        $insertdata['name'] = $v;
                        $insertdata['companyId'] = $id;
                        $insertdata['phone'] = $safeInfoData['phone'][$k];
                        Comsafeofficer::insertGetId($insertdata);
                    }
                }
            }
            if(!empty($managerInfo)) {
                foreach ($managerInfo['name'] as $k=>$v){
                    $insertdata['name'] = $v;
                    $insertdata['companyId'] = $id;
                    $insertdata['phone'] = $managerInfo['phone'][$k];
                    $insertdata['wx'] = $managerInfo['wx'][$k];
                    Commanager::insertGetId($insertdata);
                }
            }
            \Session::flash('error', '修改成功!');
            return redirect('ninesmall/firetype/'.$id);
        }

        $isset = Company::where(['comName'=>$company['comName']])->get();
        $isset = json_decode(json_encode($isset), true);
        if(!empty($isset)) {
            \Session::flash('error', '该公司已存在!');
            return back();
//            return redirect('/ninesmall/search/categoryId/'.$categoryId.'/name/'.$company['comName']);
        }

        $user = Auth::user();
        $company['userId'] = $user->id;
//        $company['project'] = $project_id;

        if(!$company['comName'] || !$company['street'])
        {
            \Session::flash('error', '公司信息有误!');
            return redirect('/ninesmall/category/'.$categoryId);
        }
        /*判断user表**/
        if (preg_match('/^[\x{4e00}-\x{9fa5}]+$/u', $company['comName']) > 0){
            $comarr = preg_split('/(?<!^)(?!$)/u', $company['comName']);
            $comstr = '';
            foreach ($comarr as $com){
                $comstr.=self::getFirstCharter($com);
            }
        }else{
            \Session::flash('error', '请填写正确的公司名称!');
            return redirect('/ninesmall/category/'.$categoryId);
        }

        $phone = User::where(['name'=>$company['comName'],'phone' => $company['leaderPhone']])->get();
        $phone = json_decode(json_encode($phone), true);
        if (!empty($phone)){
            \Session::flash('error', '法定代表人电话重复!');
            return redirect('/ninesmall/category/'.$categoryId);
        }

        $one = User::where(['name'=>$company['comName'],'account' => $comstr,'type' => 2])->get();
        $one = json_decode(json_encode($one), true);
        if (!empty($one)){
            \Session::flash('error', '该公司已存在!');
            return back();
//            return redirect('/ninesmall/search/'.$company['comName'].'/categoryId/'.$categoryId);
        }
        /*判断user表**/
        $company['type'] = 2;
        $companyId = Company::insertGetId($company);
//        dd($companyId);
        /*插入user表**/
        if ($companyId){
            /*使用事务插入*/
            DB::beginTransaction();
            try{
                $insert = User::create([
                    'name' => $company['comName'],
                    'phone' => $company['leaderPhone'],
                    'account' => $comstr,
                    'password' =>  bcrypt('1234abcd'),
                    'type' => 2,
                    'companyId' => $companyId,
                ]);
                if($insert) {
                    DB::commit();
                }
            }catch (\Exception $e) {
                DB::rollBack();
//            \Session::flash('error', $e->getMessage());
                return back();
            }

//            dd($comstr);
        }
        /*插入user表**/
        /*安全管理人员*/
        if(!empty($safeInfo))
        {
            $safeInfoData = array();
            $safeInfoData = $safeInfo;
            if(!empty($safeInfoData)) {
                foreach ($safeInfoData['name'] as $k=>$v){
                    $insertdata['name'] = $v;
                    $insertdata['companyId'] = $companyId;
                    $insertdata['phone'] = $safeInfoData['phone'][$k];
                    Comsafeofficer::insertGetId($insertdata);
                }
            }
        }
        /*主要负责人员*/
        if(!empty($managerInfo)) {
            foreach ($managerInfo['name'] as $k=>$v){
                $insertdata['name'] = $v;
                $insertdata['companyId'] = $companyId;
                $insertdata['phone'] = $managerInfo['phone'][$k];
                $insertdata['wx'] = $managerInfo['wx'][$k];
                Commanager::insertGetId($insertdata);
            }
        }

        return redirect('ninesmall/firetype/'.$companyId);
    }

    //消防非消防
    public function firetype(Request $request,int $companyId)
    {
        $company = Company::find($companyId);
        $request->session()->put('categoryId',$company->categoryId);

        if(!$company) {
            \Session::flash('error', '公司信息有误!');
            return back();
        }
        if(!$companyId){
            return redirect('/ninesmall');
        }
        $fire = 0;
        $nofire = 0;
        $zhijian = 0;
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $fire += $v->stepStatus;
                }
                if($v->typeStatus == 2) {
                    $nofire += $v->stepStatus;
                }
                if($v->typeStatus == 5) {
                    $zhijian += $v->stepStatus;
                }
            }
        }
        $comcheckInfo = Comcheck::where(['companyId'=>$companyId])->select('id','status')->first();

        if($comcheckInfo) {
            $checkId = $comcheckInfo['id'];
        } else {
            $user = Auth::user();
            $check['companyId'] = $companyId;
            $check['created'] = date('Y-m-d H:i:s',time());
            $check['userId'] = $user->id;
            $checkId = Comcheck::insertGetId($check);
        }
        $request->session()->put('companyId', $companyId);
        $request->session()->put('checkId', $checkId);
        $detail = Comcheckdetail::whereNull('groupId')->where(['checkId'=>$checkId])->get();
        $detail = json_decode(json_encode($detail), true);
        ///////
        ///
        $companyId = $request->session()->get('companyId',0);
        $categoryId = $request->session()->get('categoryId',0);
        if(!$companyId){
            return redirect('/ninesmall');
        }
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        $steps = [
            '1'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>1])->first()->id,
                'status' => 0,
                'type' => 1,
                'title'=>'基础档案'
            ],
            '2'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>1])->first()->id,
                'status' => 0,
                'type' => 1,
                'title'=>'作业现场'
            ],
            '3'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>2])->first()->id,
                'status' => 0,
                'type' => 2,
                'title'=>'基础档案'
            ],
            '4'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>2])->first()->id,
                'status' => 0,
                'type' => 2,
                'title'=>'作业现场'
            ],
            '5'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>5])->first()->id,
                'status' => 0,
                'type' => 5,
                'title'=>'基础档案'
            ],
            '6'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>5])->first()->id,
                'status' => 0,
                'type' => 5,
                'title'=>'作业现场'
            ],

        ];
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == 1) {
                    $steps[$v->stepStatus]['status'] = 1 ;
                }
                if($v->typeStatus == 2 && $v->stepStatus == 1) {
                    $steps[3]['status'] = 1 ;
                }
                if($v->typeStatus == 2 && $v->stepStatus == 2) {
                    $steps[4]['status'] = 1 ;
                }
                if($v->typeStatus == 5 && $v->stepStatus == 1) {
                    $steps[5]['status'] = 1 ;
                }
                if($v->typeStatus == 5 && $v->stepStatus == 2) {
                    $steps[6]['status'] = 1 ;
                }
            }
        }
        return view('ninesmall.firetype')
            ->with('companyId',$companyId)
            ->with('fire',$fire)
            ->with('zhijian',$zhijian)
            ->with('detail',$detail)
            ->with('checkId',$checkId)
            ->with('steps',$steps)
            ->with('nofire',$nofire);
    }

    //人物环管
    public function choose(Request $request,int $firetype)
    {
        $companyId = $request->session()->get('companyId',0);
        $categoryId = $request->session()->get('categoryId',0);
        if(!$companyId){
            return redirect('/ninesmall');
        }
        $request->session()->put('firetype', $firetype);
        if(!$firetype){
            \Session::flash('error', '公司信息有误!');
            return back();
        }
        $comcheckstep = new Comcheckstep();
        $fireinfo = $comcheckstep->getfiretype($companyId);
        $id1 = Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>$firetype])->first();
        $id2 = Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>$firetype])->first();
        if (empty($id1->id)){
            \Session::flash('error', '检查信息未录入!');
            return back();
        }
        if (empty($id2->id)){
            \Session::flash('error', '检查信息未录入!');
            return back();
        }
        $steps = [
            '1'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>1,'type'=>$firetype])->first()->id,
                'status' => 0,
                'title'=>'基础档案'
            ],
            '2'=>[
                'id' => Checkgroup::where(['categoryId'=>$categoryId,'status'=>2,'type'=>$firetype])->first()->id,
                'status' => 0,
                'title'=>'作业现场'
            ],
        ];
        if(count($fireinfo)){
            foreach ($fireinfo as $k => $v) {
                if($v->typeStatus == $firetype) {
                    $steps[$v->stepStatus]['status'] = 1 ;
                }
            }
        }
        return view('ninesmall.choose')
            ->with('companyId',$companyId)
            ->with('steps',$steps);
    }

    /**
     * 项目统计导出
     */
    public function export()
    {
        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH');
        $objActSheet->setCellValue("A1","检查情况统计表");
        $objActSheet->mergeCells('A1:AH1');
        $objActSheet->getStyle('A1')->getAlignment()->setWrapText(true);
        $objActSheet->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        $objActSheet->getStyle('A1')->getFont()->setName('黑体');
        $objActSheet->getStyle('A1')->getFont()->setSize(20);
        $objActSheet->getStyle('A1')->getFont()->setBold(true);
        //part1
        $objActSheet->setCellValue("A2","序号");
        $objActSheet->setCellValue("B2","企业名称");
        $objActSheet->setCellValue("C2","行业类别");
        $objActSheet->setCellValue("D2","企业地址");
        $objActSheet->setCellValue("E2","员工人数");
        $objActSheet->setCellValue("F2","占地面积");
        $objActSheet->setCellValue("G2","固定资产");
        $objActSheet->setCellValue("H2","年销售收入");
        $objActSheet->setCellValue("I2","法定代表人");
        $objActSheet->setCellValue("J2","联系电话");
        $objActSheet->setCellValue("K2","联系人");
        $objActSheet->setCellValue("L2","联系电话");
        $objActSheet->getStyle('B2:L2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('B2:L2')->getFill()->getStartColor()->setARGB('FFFF0000');
        $line1 =  ['B','C','D','E','F','G','H','I','J','K','L','M','N'];
        foreach ($line1 as $l) {
            $objActSheet->mergeCells($l . '2:' . $l . '3');
        }
        //part2
        $objActSheet->setCellValue("M2","检查日期");
        $objActSheet->setCellValue("N2","检查人员");
        $objActSheet->getStyle('M2:N2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('M2:N2')->getFill()->getStartColor()->setARGB('FFFF8000');//黄褐
        //part3
        $objActSheet->setCellValue("O2","消防类");
        $objActSheet->setCellValue("O3","人的因素(条)");
        $objActSheet->setCellValue("P3","物的因素(条)");
        $objActSheet->setCellValue("Q3","环境因素(条)");
        $objActSheet->setCellValue("R3","管理因素(条)");
        $objActSheet->setCellValue("S3","隐患总数(条)");
        $objActSheet->mergeCells("O2:S2");
        $objActSheet->getStyle('O2:S3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('O2:S3')->getFill()->getStartColor()->setARGB('FFFFFF00');//黄色
        //part4
        $objActSheet->setCellValue("T2","非消防类");
        $objActSheet->setCellValue("T3","人的因素(条)");
        $objActSheet->setCellValue("U3","物的因素(条)");
        $objActSheet->setCellValue("V3","环境因素(条)");
        $objActSheet->setCellValue("W3","管理因素(条)");
        $objActSheet->setCellValue("X3","隐患总数(条)");
        $objActSheet->mergeCells("T2:X2");
        $objActSheet->getStyle('T2:X3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('T2:X3')->getFill()->getStartColor()->setARGB('FF80E000');//墨绿
        //part5
        $objActSheet->setCellValue("Y2","复查日期");
        $objActSheet->setCellValue("Z2","复查人员");
        $objActSheet->mergeCells("Y2:Y3");
        $objActSheet->mergeCells("Z2:Z3");
        $objActSheet->getStyle('Y2:Z2')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('Y2:Z2')->getFill()->getStartColor()->setARGB('FFECECEC');//银白
        //part6
        $objActSheet->setCellValue("AA2","消防类");
        $objActSheet->setCellValue("AA3","已整改(条)");
        $objActSheet->setCellValue("AB3","部分整改(条)");
        $objActSheet->setCellValue("AC3","未整改(条)");
        $objActSheet->setCellValue("AD3","整改率(%)");
        $objActSheet->mergeCells("AA2:AD2");
        $objActSheet->getStyle('AA2:AD3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('AA2:AD3')->getFill()->getStartColor()->setARGB('FF0088FF');//天蓝
        //part7
        $objActSheet->setCellValue("AE2","消防类");
        $objActSheet->setCellValue("AE3","已整改(条)");
        $objActSheet->setCellValue("AF3","部分整改(条)");
        $objActSheet->setCellValue("AG3","未整改(条)");
        $objActSheet->setCellValue("AH3","整改率(%)");
        $objActSheet->mergeCells("AE2:AH2");
        $objActSheet->getStyle('AE2:AH3')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
        $objActSheet->getStyle('AE2:AH3')->getFill()->getStartColor()->setARGB('FF9000FF');//紫色
        //统一设置左右居中、字号、宽度
        foreach ($letter as $l){
            $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
            $objActSheet->getStyle($l.'3')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
            $objActSheet->getStyle($l.'2')->getFont()->setSize(13);
            $objActSheet->getStyle($l.'3')->getFont()->setSize(13);
            $objActSheet->getColumnDimension($l)->setWidth(19);
        }
        //单独设置宽度
        $objActSheet->getColumnDimension('A')->setWidth(7);
        $objActSheet->getColumnDimension('B')->setWidth(40);
        $objActSheet->getColumnDimension('D')->setWidth(40);

        /**填充内容*/
        $orirow = 4;
        $i = 1;
        $project_id = $_GET['project'];
        $list  = Comcheck::leftJoin('company','comcheck.companyId','company.id')->select('comcheck.*','company.project')->where('company.project','=',$project_id)->orderBy('comcheck.id','desc')->get();

        $comcheckId = [];
        $companyId = [];
        foreach ($list as $k=>$v){
            $companyId[] = $v['companyId'];
            $comcheckId[] = $v['id'];
        }
        $company = Company::whereIn('id',$companyId)->get();
        $areaid = [];
        $categoryId = [];
        foreach ($company as $k=>$v){
            array_push($categoryId,$v->category);
            (in_array($v->province,$areaid)||(empty($v->province)))?'':array_push($areaid,$v->province);
            (in_array($v->city,$areaid)||(empty($v->city)))?'':array_push($areaid,$v->city);
            (in_array($v->district,$areaid)||(empty($v->district)))?'':array_push($areaid,$v->district);
            (in_array($v->street,$areaid)||(empty($v->street)))?'':array_push($areaid,$v->street);
        }
        $category = Checkcategory::whereIn('id',$categoryId)->get();
        $area = Area::whereIn('id',$areaid)->get();
        $comcheckdetail = Comcheckdetail::whereIn('checkId',$comcheckId)->where('status','=',2)->get();
        $comcheckagain = Comcheckagain::whereIn('checkId',$comcheckId)->get();
        $comcheckagainId = [];
        foreach ($comcheckagain as $k=>$v){
            $comcheckagainId[] =$v['id'];
        }
        $comcheckagaindetail = Comcheckagaindetail::leftJoin('checkentry','comcheckagaindetail.entryId','checkentry.id')
            ->leftJoin('checkgroup','checkentry.groupId','checkgroup.id')
            ->select('comcheckagaindetail.*','checkentry.entry','checkgroup.status as groupstatus','checkgroup.type as grouptype')
            ->whereIn('comcheckagaindetail.checkId',$comcheckagainId)->get();
        /*获取初查详情*/
        $comcheckid = [];

        foreach ($list as $v){
            $comcheckid[] = $v['id'];
        }
        $comcheckdetailtree =  Comcheckdetail::leftJoin('checkentry','comcheckdetail.entryId','checkentry.id')
            ->leftJoin('checkgroup','checkentry.groupId','checkgroup.id')
            ->select('comcheckdetail.*','checkentry.entry','checkgroup.status as groupstatus','checkgroup.type as grouptype')
            ->whereIn('comcheckdetail.checkId',$comcheckid)->where('comcheckdetail.status','=',2)
            ->get();
        $comcheckdetailtree = json_decode(json_encode($comcheckdetailtree), true);
        /*获取初查详情*/

        foreach ($list as $u) {
            $adress = '';
            $ren = 0;
            $fren = 0;
            $wu = 0;
            $fwu = 0;
            $huan = 0;
            $fhuan = 0;
            $guan = 0;
            $fguan = 0;
            $fucha = 0;
            $yzhenggai = 0;
            $bfzhenggai = 0;
            $wzhenggai = 0;
            $fyzhenggai = 0;
            $fbfzhenggai = 0;
            $fwzhenggai = 0;
            $fuchadate = '';
            $fuchauser = '';
            foreach ($area as $a) {
                if ($u->company->city == $a->id){
                    $adress .=$a->name;
                }
                if ($u->company->district == $a->id) {
                    $adress .=$a->name;
                }
                if ($u->company->street == $a->id) {
                    $adress .=$a->name;

                }
            }
            $objActSheet->setCellValue("A".$orirow,$i);
            $objActSheet->setCellValue("B".$orirow,$u->company->comName);
            foreach ($category as $k=>$v){
                if ($u->company->category == $v->id){
                    $objActSheet->setCellValue("C".$orirow,$v->name);
                }
            }
            foreach ($comcheckdetailtree as $k1=>$u1){
                if ($u1['grouptype'] == 1){
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 1){
                        $ren += 1;
                    }
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 2){
                        $wu += 1;
                    }
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 3){
                        $huan += 1;
                    }
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 4){
                        $guan += 1;
                    }
                }
                if ($u1['grouptype'] == 2){
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 1){
                        $fren += 1;
                    }
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 2){
                        $fwu += 1;
                    }
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 3){
                        $fhuan += 1;
                    }
                    if ($u1['checkId'] == $u['id'] && $u1['groupstatus'] == 4){
                        $fguan += 1;
                    }
                }

            }

            foreach ($comcheckagain as $v) {
                if ($v->checkId == $u->id){
                    $fuchauser = $fuchauser.\App\User::find($v->userId)->name;
                    $fuchadate = $fuchadate.date('Y.m.d',$v->checkTime);
                }
                foreach ($comcheckagaindetail as $v1) {
                    if ($v->checkId == $u->id && $v->id == $v1->checkId) {
                        if ($v1['grouptype'] == 1){
                            if ($v1['status'] == 1){
                                $wzhenggai ++;
                            }
                            if ($v1['status'] == 2){
                                $bfzhenggai ++;
                            }
                            if ($v1['status'] == 3){
                                $yzhenggai ++;
                            }
                        }
                        if ($v1['grouptype'] == 2){
                            if ($v1['status'] == 1){
                                $fwzhenggai ++;
                            }
                            if ($v1['status'] == 2){
                                $fbfzhenggai ++;
                            }
                            if ($v1['status'] == 3){
                                $fyzhenggai ++;
                            }
                        }
                    }
                }
            }
            $objActSheet->setCellValue("D".$orirow,$adress.$u->company->address);
            $objActSheet->setCellValue("E".$orirow,$u->company->workersNum);
            $objActSheet->setCellValue("F".$orirow,$u->company->space);
            $objActSheet->setCellValue("G".$orirow,$u->company->assets);
            $objActSheet->setCellValue("H".$orirow,$u->company->income);
            $objActSheet->setCellValue("I".$orirow,$u->company->leader);
            $objActSheet->setCellValue("J".$orirow,$u->company->leaderPhone);
            $objActSheet->setCellValue("K".$orirow,$u->company->leader);
            $objActSheet->setCellValue("L".$orirow,$u->company->leaderPhone);
            $objActSheet->setCellValue("M".$orirow,$u->created);
            $objActSheet->setCellValue("N".$orirow,$u->users->name);
            $objActSheet->setCellValue("O".$orirow,$ren);
            $objActSheet->setCellValue("P".$orirow,$wu);
            $objActSheet->setCellValue("Q".$orirow,$huan);
            $objActSheet->setCellValue("R".$orirow,$guan);
            $objActSheet->setCellValue("S".$orirow,$ren+$wu+$huan+$guan);
            $objActSheet->setCellValue("T".$orirow,$fren);
            $objActSheet->setCellValue("U".$orirow,$fwu);
            $objActSheet->setCellValue("V".$orirow,$fhuan);
            $objActSheet->setCellValue("W".$orirow,$fguan);
            $objActSheet->setCellValue("X".$orirow,$fren+$fwu+$fhuan+$fguan);
            $objActSheet->setCellValue("Y".$orirow,$fuchadate);
            $objActSheet->setCellValue("Z".$orirow,$fuchauser);
            $objActSheet->setCellValue("AA".$orirow,$yzhenggai);
            $objActSheet->setCellValue("AB".$orirow,$bfzhenggai);
            $objActSheet->setCellValue("AC".$orirow,$wzhenggai);
            if (!empty($yzhenggai+$wzhenggai+$bfzhenggai)){
                $objActSheet->setCellValue("AD".$orirow,sprintf("%.2f",$yzhenggai/($yzhenggai+$wzhenggai+$bfzhenggai)*100).'%');
            }
            $objActSheet->setCellValue("AE".$orirow,$fyzhenggai);
            $objActSheet->setCellValue("AF".$orirow,$fbfzhenggai);
            $objActSheet->setCellValue("AG".$orirow,$fwzhenggai);
            if (!empty($fyzhenggai + $fwzhenggai + $fbfzhenggai)) {
                $objActSheet->setCellValue("AH" . $orirow, sprintf("%.2f", $yzhenggai / ($fyzhenggai + $fwzhenggai + $fbfzhenggai) * 100) . '%');
            }
            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 4;$x<=$orirow;$x++){
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
            }

        }
        for ($x=1; $x<=($orirow+10); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:AH'.($orirow+10))->applyFromArray($styleArray);//设置粗边框
        $objActSheet->getRowDimension(1)->setRowHeight(40);//单独设置行高度
        $objActSheet->getRowDimension(2)->setRowHeight(40);//单独设置行高度
        $date = Carbon::now()->toDateString();//表名前缀日期
        $name = \App\Model\Project::find($_GET['project'])->project_name;

        $write = new \PHPExcel_Writer_Excel5($excel);

        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="'.$name.''."项目检查统计".'.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');

        exit();
        $cellData = ['序号','隐患统计','排查地点','排查人'];
        $date = Carbon::now()->toDateString();
        $name = Project::find($_GET['project'])->project_name;
        \Maatwebsite\Excel\Facades\Excel::create($name.'项目检查统计',function($excel) use ($cellData){
            $excel->sheet('score', function($sheet) use ($cellData){
                $list = self::GetTodayList();
                $comcheckId = [];
                $companyId = [];
                foreach ($list as $k=>$v){
                    $companyId[] = $v['companyId'];
                    $comcheckId[] = $v['id'];
                }
                $company = Company::whereIn('id',$companyId)->get();
                $areaid = [];
                foreach ($company as $k=>$v){
                    (in_array($v->province,$areaid)||(empty($v->province)))?'':array_push($areaid,$v->province);
                    (in_array($v->city,$areaid)||(empty($v->city)))?'':array_push($areaid,$v->city);
                    (in_array($v->district,$areaid)||(empty($v->district)))?'':array_push($areaid,$v->district);
                    (in_array($v->street,$areaid)||(empty($v->street)))?'':array_push($areaid,$v->street);
                }
                $area = Area::whereIn('id',$areaid)->get();
                $comcheckdetail = Comcheckdetail::whereIn('checkId',$comcheckId)->where('status','=',2)->get();
                $comcheckagain = Comcheckagain::whereIn('checkId',$comcheckId)->get();
                $comcheckagainId = [];
                foreach ($comcheckagain as $k=>$v){
                    $comcheckagainId[] =$v['id'];
                }
                $comcheckagaindetail = Comcheckagaindetail::whereIn('checkId',$comcheckagainId)->where('status','=',3)->get();                $company = Company::whereIn('id',$companyId)->get();
                $sheet->setWidth(array(
                    'A'     =>  5,
                    'B'     =>  42,
                    'C'     =>  30,
                    'D'     =>  12
                ))->rows($cellData)->setFontSize(12);
                $sheet->cells('A1:D1', function($cells) {
                    $cells->setBackground('#93b7f3');
                    $cells->setFontWeight('bold');
                    $cells->setFontSize(14);
                });
                $sheet->cell('A2',$cellData[0]);
                $sheet->cell('B1',$cellData[1]);
                $sheet->cell('C1',$cellData[2]);
                $sheet->cell('D1',$cellData[3]);
                $orirow = 2;
                $i = 1;
                foreach ($list as $u){
                    $adress = '';
                    $chucha = 0;$fucha = 0;
                    foreach ($comcheckdetail as $v){
                        if ($v->checkId == $u->id){
                            $chucha ++;
                        }
                    }
                    foreach ($comcheckagain as $v) {
                        foreach ($comcheckagaindetail as $v1) {
                            if ($v->checkId == $u->id && $v->id == $v1->checkId) {
                                $fucha++;
                            }
                        }
                    }
                    foreach ($area as $a) {
                        if ($u->company->city == $a->id){
                            $adress .=$a->name;
                        }
                        if ($u->company->district == $a->id) {
                            $adress .=$a->name;
                        }
                        if ($u->company->street == $a->id) {
                            $adress .=$a->name;

                        }
                    }
                    $sheet->cell('A'.$orirow,$i);
                    $sheet->cell('B'.$orirow,$u->company->comName.'初查时共有'.$chucha.'条隐患，复查时已整改'.$fucha.'条');
                    $sheet->cell('C'.$orirow,$adress.$u->company->address);
                    $sheet->cell('D'.$orirow,$u->users->name);
                    $orirow ++;
                    $i++;
                }
                $sheet->rows($cellData);
            });
        })->export('xls');
    }



    public static function getFirstCharter($str)
    {
        if (empty($str)) {
            return '';
        }
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284) return 'a';
        if ($asc >= -20283 && $asc <= -19776) return 'b';
        if ($asc >= -19775 && $asc <= -19219) return 'c';
        if ($asc >= -19218 && $asc <= -18711) return 'd';
        if ($asc >= -18710 && $asc <= -18527) return 'e';
        if ($asc >= -18526 && $asc <= -18240) return 'f';
        if ($asc >= -18239 && $asc <= -17923) return 'g';
        if ($asc >= -17922 && $asc <= -17418) return 'h';
        if ($asc >= -17417 && $asc <= -16475) return 'j';
        if ($asc >= -16474 && $asc <= -16213) return 'k';
        if ($asc >= -16212 && $asc <= -15641) return 'l';
        if ($asc >= -15640 && $asc <= -15166) return 'm';
        if ($asc >= -15165 && $asc <= -14923) return 'n';
        if ($asc >= -14922 && $asc <= -14915) return 'o';
        if ($asc >= -14914 && $asc <= -14631) return 'p';
        if ($asc >= -14630 && $asc <= -14150) return 'q';
        if ($asc >= -14149 && $asc <= -14091) return 'r';
        if ($asc >= -14090 && $asc <= -13319) return 's';
        if ($asc >= -13318 && $asc <= -12839) return 't';
        if ($asc >= -12838 && $asc <= -12557) return 'w';
        if ($asc >= -12556 && $asc <= -11848) return 'x';
        if ($asc >= -11847 && $asc <= -11056) return 'y';
        if ($asc >= -11055 && $asc <= -10247) return 'z';
        return null;
    }

}
